package cn.medemede.dao;


import cn.medemede.dbc.DatabaseConnection;
import cn.medemede.model.UserpwdBean;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserpwdDao {

    public static boolean creat(UserpwdBean userpwdBean) throws Exception {
        Connection connection= DatabaseConnection.getConnection();
        String InsertSQL = "INSERT INTO userpwd (username,password) VALUES (?,?)";
        PreparedStatement preparedStatement=connection.prepareStatement(InsertSQL);
        preparedStatement.setString(1,userpwdBean.getUsername());
        preparedStatement.setString(2,userpwdBean.getPassword());
        int flag=preparedStatement.executeUpdate();
        connection.close();
        preparedStatement.close();
        return flag>0;
    }


    public static boolean remove(UserpwdBean userpwdBean) throws Exception {
        Connection connection=DatabaseConnection.getConnection();
        String DeleteSQL1 = "DELETE from users where username=?";
        String DeleteSQL2 = "DELETE from userpwd where username=?";
        PreparedStatement preparedStatement=connection.prepareStatement(DeleteSQL1);
        preparedStatement.setString(1,userpwdBean.getUsername());
        int flag1=preparedStatement.executeUpdate();
        preparedStatement=connection.prepareStatement(DeleteSQL2);
        preparedStatement.setString(1,userpwdBean.getUsername());
        int flag2=preparedStatement.executeUpdate();
        connection.close();
        preparedStatement.close();
        return flag1 > 0&&flag2>0;
    }


    public static boolean find(UserpwdBean userpwdBean) throws Exception {
        Connection connection=DatabaseConnection.getConnection();
        String FindSQL = "select * from userpwd where username=? and password=?";
        PreparedStatement preparedStatement=connection.prepareStatement(FindSQL);
        preparedStatement.setString(1,userpwdBean.getUsername());
        preparedStatement.setString(2,userpwdBean.getPassword());
        ResultSet rs=preparedStatement.executeQuery();

        boolean f=rs.next();
        rs.close();
        preparedStatement.close();
        connection.close();
        return f;

    }

    public static boolean update(UserpwdBean userpwdBean) throws Exception {
        Connection connection=DatabaseConnection.getConnection();
        String UpdateSQL = "UPDATE userpwd SET password=?";
        PreparedStatement preparedStatement=connection.prepareStatement(UpdateSQL);
        preparedStatement.setString(1,userpwdBean.getPassword());
        int flag=preparedStatement.executeUpdate();
        connection.close();
        preparedStatement.close();
        return flag>0;
    }
}
